<template>
  <div>
    <a-card title="日常收支">
      <a-row gutter="16">
        <a-col :span="4" style="padding-left: 0px; padding-right: 0px; width: 120px;margin-right: 0px;margin-left: 10px;">
                <a-select v-model="searchForm.is_void" style="width: 100%" placeholder="收支状态" allowClear>
                  <a-select-option v-for="item in is_Void_Options" :key="item.id" :value="item.value">
                    {{ item.name }}
                  </a-select-option>
                </a-select>          
        </a-col>
        <a-col :span="4" style="padding-left: 0px; padding-right: 0px; width: 120px;margin-right: 0px;margin-left: 10px;">
                <a-select showSearch v-model="searchForm.type" style="width: 100%" :filterOption="filterOption" allowClear placeholder="收支类型" >
                  <a-select-option v-for="item in typeItems" :key="item.id" :value="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
            </a-col>
        <a-col :span="4" style="padding-left: 0px; padding-right: 0px; width: 120px;margin-right: 0px;margin-left: 10px;">
                <a-select showSearch v-model="searchForm.charge_item" style="width: 100%" :filterOption="filterOption" allowClear placeholder="收支项目" >
                  <a-select-option v-for="item in chargeItems_new" :key="item.id" :value="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
            </a-col>
            <a-col :span="4" style="padding-left: 0px; padding-right: 0px; width: 140px;margin-right: 0px;margin-left: 10px;" v-if="searchForm.type!='income'">
            <a-select v-model="searchForm.supplier" style="width: 100%" allowClear placeholder="供应商" showSearch :filterOption="filterOption" >
              <a-select-option v-for="item in suppliersItems" :key="item.id" :value="item.id">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-col>
            <a-col :span="4" style="padding-left: 0px; padding-right: 0px; width: 140px;margin-right: 0px;margin-left: 10px;" v-if="searchForm.type!='expenditure'">
            <a-select v-model="searchForm.client" style="width: 100%" allowClear placeholder="客户" showSearch :filterOption="filterOption" >
              <a-select-option v-for="item in clientsItems" :key="item.id" :value="item.id">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-col>
        <a-col :span="24" :md="6" :xl="4" style="max-width: 140px; margin-bottom: 12px;">
          <a-input v-model="searchForm.search" placeholder="编号/备注" allowClear />
        </a-col>
        <a-col :span="3" :md="3" :xl="3"  style="padding-left: 0px; padding-right: 0px; width: 280px;margin-right: 0px;margin-left: 0px;">
            处理时间:<a-range-picker v-model="dateRange" @change="changeDate" style="width: 200px;" :ranges="ranges"/>
        </a-col>
        <a-col :span="3" :md="3" :xl="3"  style="width: 280px;margin-left: 10px;">
              <a-button-group> 
                <a-button type="primary" :loading="loading" @click="search"><a-icon type="search" />查询</a-button>    
                <a-button :loading="downloadLoading" @click="handleDownload"><a-icon type="file-excel" />导出</a-button>    
              </a-button-group>
        </a-col>
        <div style="margin-bottom: 12px; float: right;">
          <a-button type="primary" icon="plus" style="margin: 0 8px;" @click="openFormModal(form)">新增日常收支</a-button>
        </div>
      </a-row>
      <a-row style="margin-top: 0px;">
      查询结果-> 收支项目数：共{{ total.count }}(项)，应{{ (searchForm.type=='expenditure'?'付':'收') }}金额：{{ total.total_amount }}(元)，实{{ (searchForm.type=='expenditure'?'付':'收') }}金额：{{ total.charge_amount }}(元)      
    </a-row>
      <a-row style="margin-top: 12px;">
        <a-table size="small" :columns="columns" :dataSource="items" rowKey="id" :loading="loading" :pagination="pagination"
          @change="tableChange">
          <div slot="is_active" slot-scope="value">
            <a-tag :color="value ? 'green' : 'red'">{{value ? '激活' : '冻结'}}</a-tag>
          </div>
          <div slot="action" slot-scope="value, item">
            <a-button-group>
              <a-popconfirm title="确定作废吗?" @confirm="voidItem(item)">
                <a-button type="danger" size="small" :disabled="item.is_void">{{ item.is_void ? '已作废' : '作废'}}</a-button>
              </a-popconfirm>
            </a-button-group>
          </div>
        </a-table>
      </a-row>
    </a-card>
    <form-modal v-model="visible" :form="targetItem" :clientsItems="clientsItems" :chargeItems="chargeItems" :suppliersItems="suppliersItems" :handlerItems="handlerItems" :accountsItems="accountsItems" @create="create" @update="update" />
  </div>
</template>

<script>
  import { clientsOption, suppliersOption, chargeItemsOption, userOption, accountsOption } from '@/api/option'
  import { getChargeOrderNumber } from '@/api/data'
  import { chargeOrdersList, chargeOrdersVoid } from '@/api/finance'
  import { datetimeToString } from '@/utils/functions';
  import { List} from '@/api/common'

  export default {
    name: 'Warehouse',
    components: {
      FormModal: () => import('./FormModal.vue'),
    },
    data() {
      return {
        typeItems: [
          { id: 'income', name: '收入' },
          { id: 'expenditure', name: '支出' }
        ],
        is_Void_Options:[
          {
            id:1,
            name:"所有",
            value:null
          },
          {
            id:2,
            name:"正常",
            value:false
          },
          {
            id:3,
            name:"已作废",
            value:true
          },
        ],
        downloadList: [],
        dateRange: [moment().startOf('day'), moment().startOf('day')],//获取本月开始第一天到今天
        ranges: {
        '今日': [moment().startOf('day'), moment().startOf('day')],
        '昨日': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
        '本周': [moment().week(moment().week()).startOf('week'), moment().week(moment().week()).endOf('week')],
        '上周': [moment().subtract(1,'week').startOf('week'), moment().subtract(1,'week').endOf('week')],
        '本月': [moment().startOf('month'), moment().startOf('day')],
        '上月': [moment().subtract(1,'month').startOf('month'), moment().subtract(1,'month').endOf('month')],
       },
        columns: [
          {
            title: '序号',
            dataIndex: 'index',
            key: 'index',
            customRender: (value, item, index) => {
              return (this.pagination.current-1)*this.pagination.pageSize+index + 1
            },
          },
          {
            title: '编号',
            dataIndex: 'number',
          },
          {
            title: '收支类型',
            dataIndex: 'type_display'
          },
          {
            title: '客户',
            dataIndex: 'client_name'
          },
          {
            title: '供应商',
            dataIndex: 'supplier_name'
          },
          {
            title: '收支项目',
            dataIndex: 'charge_item_name'
          },
          {
            title: '结算账户',
            dataIndex: 'account_name'
          },
          {
            title: '应收/付金额',
            dataIndex: 'total_amount'
          },
          {
            title: '实收/付金额',
            dataIndex: 'charge_amount'
          },
          {
            title: '经手人',
            dataIndex: 'handler_name'
          },
          {
            title: '处理时间',
            dataIndex: 'handle_time'
          },
          {
            title: '备注',
            dataIndex: 'remark'
          },
          {
            title: '操作',
            dataIndex: 'action',
            scopedSlots: { customRender: 'action' },
            width: '156px'
          },
        ],
        searchForm: { search: '', is_void:false,page: 1, page_size: 15,type:'expenditure' },
        pagination: { current: 1, total: 0, pageSize: 15 },
        loading: false,
        items: [],
        clientsItems: [],
        suppliersItems: [],
        chargeItems: [],
        handlerItems: [],
        accountsItems: [],
        visible: false,
        targetItem: {},
        form: {},
        importLoading: false,
        total:{
          count:0,
          total_amount:0,
          charge_amount:0
        },
      };
    },
    computed: {
      chargeItems_new:{
      get() {
        return this.chargeItems.filter(i=>i.type==this.searchForm.type);
      },
    },
    },
    methods: {
      getNewdownloadList(downloadList) {
          let o={
              index:'合计',
              total_amount:0,
              charge_amount:0
          }
          downloadList.forEach(e => {             
              e.is_void=e.is_void?'已作废':"正常"
          });
          if (downloadList) {
              let i=0
              downloadList.forEach(e => {
                  i+=1
                  e['index'] = i
                  e.total_amount = parseFloat(e.total_amount)
                  e.charge_amount = parseFloat(e.charge_amount)
                  o.total_amount+=e.total_amount
                  o.charge_amount+=e.charge_amount
              });
              downloadList.push(o)
          } else {
            downloadList = []
          }
      },
      handleDownload() {
        this.loading = true;
        this.downloadLoading = true;
        this.searchForm.start_date=this.dateRange.length > 0 ? this.dateRange[0].format('YYYY-MM-DD') : null
        this.searchForm.end_date=this.dateRange.length > 0 ? this.dateRange[1].format('YYYY-MM-DD') : null
        this.searchForm.page_size=9999
        if (this.searchForm.end_date) {
            this.searchForm.end_date = moment(this.searchForm.end_date).add(1, 'days').format('YYYY-MM-DD');
          }
          List(this.searchForm,'charge_orders').then(response  => {
          const resp = response.data;        
          this.downloadList = response.results;
          this.getNewdownloadList(this.downloadList) 
          // this.downloadList.forEach(e => {
          //     e.jgry_items=this.jgry_items2names(e.jgry_items)
          //     e.is_void=e.is_void?'已作废':"正常"
          // });
          // console.log('this.downloadList:',this.downloadList )
          this.searchForm.page_size=15
          import("@/vendor/Export2ExcelNew").then(excel => {
            const tHeader1 = [
              "序号",
              "收支类型",
              "供应商",
              "收支项目",
              "结算账户",
              "应收/付金额(元)",
              "实收/付金额(元)",
              "经手人",
              "处理时间",
            ];
            const filterVal = [
              "index",
              "type_display",
              "supplier_name",
              "charge_item_name",
              "account_name",
              "total_amount",
              "charge_amount",
              "handler_name",
              "handle_time",
            ];
            //const filterVal = tHeader;
            //不要将下载数据与显示数据列表用同一个变量，否则要出问题
            const list = this.downloadList;
            let downloadList = list;
  
            const data = this.formatJson(filterVal, downloadList);
            console.log('data:',data)
            const title = ["日常收支"+datetimeToString(new Date())];
            const sheetname = "日常收支";
            const merges = [ "A1:I1"];
            excel.export_json_to_excel({
              title,
              header: tHeader1,
              // multiHeader:[tHeader1],            
              data,
              filename: "日常收支"+datetimeToString(new Date()),
              merges,
              // autoWidth: this.autoWidth,
              autoWidth: this.autoWidth,
              bookType: this.bookType,
              sheetname
            });
            this.loading = false;
            this.downloadLoading = false;
          });
        });
      },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
      // 将输入的内容与显示的内容进行匹配
      filterOption (value, option) {
        return option.componentOptions.children[0].text.indexOf(value) >= 0
      },
      initialize() {
        suppliersOption({ page_size: 999999, is_active: true }).then(data => {
          this.suppliersItems = data.results;
        });
        clientsOption({ page_size: 999999, is_active: true }).then(data => {
          this.clientsItems = data.results;
        });
        chargeItemsOption({ page_size: 999999 }).then(data => {
          this.chargeItems = data.results;
        });
        this.list();
      },
      list() {
        this.loading = true;
        this.searchForm.page = 1;
        // this.pagination.current = 1;
        this.searchForm.start_date=this.dateRange.length > 0 ? this.dateRange[0].format('YYYY-MM-DD') : null
        this.searchForm.end_date=this.dateRange.length > 0 ? this.dateRange[1].format('YYYY-MM-DD') : null
        if (this.searchForm.end_date) {
            this.searchForm.end_date = moment(this.searchForm.end_date).add(1, 'days').format('YYYY-MM-DD');
        }
        chargeOrdersList(this.searchForm).then(data => {
          this.pagination.total = data.count;
          this.total.count = data.count;
          this.total.total_amount = data.total_amount;
          this.total.charge_amount = data.charge_amount;
          this.items = data.results;
        }).finally(() => {
          this.loading = false;
        });
      },
      tableChange(pagination, filters, sorter) {
        this.searchForm.page = pagination.current;
        this.pagination.current = pagination.current;
        this.searchForm.ordering = `${sorter.order == 'descend' ? '-' : ''}${sorter.field}`;
        this.list();
      },
      create(item) {
        // this.items.splice(0, 0, item);
        this.list();
      },
      update(item) {
        this.items.splice(this.items.findIndex(i => i.id == item.id), 1, item);
      },
      search() {

        this.list();
      },
      openFormModal(item) {
        this.form.handle_time=datetimeToString(new Date())
        this.form.type='expenditure'


        userOption({ page_size: 999999, is_active: true }).then(data => {
          this.handlerItems = data.results.filter(i=>i.is_manager==true);
        });
        accountsOption({ page_size: 999999, is_active: true }).then(data => {
          this.accountsItems = data.results;
        });
        getChargeOrderNumber().then(data => {
          this.targetItem = { ...item, ...{ number: data.number } };
        });
        this.visible = true;
      },
      voidItem(item) {
        chargeOrdersVoid({ id: item.id }).then(() => {
          this.$message.success('作废成功');
          this.list();
        });
      },
    },
    mounted() {
      this.initialize();
    },
  }
</script>